package ru.ifmo.mlarinsky.classificator.gui;

import fi.javasom.jsom.SomNode;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.util.List;
import javax.swing.*;
import javax.swing.border.LineBorder;
import net.miginfocom.swing.MigLayout;
import ru.ifmo.mlarinsky.classificator.map.MapNode;
import ru.ifmo.mlarinsky.classificator.model.Instrument;

public class MapNodePanel extends JPanel {
    private static final Dimension MINIMUM_SIZE = new Dimension(20, 20);
    private static final int BORDER_THICKNESS = 1;
    private final MapNode node;

    public MapNodePanel(MapNode node) {
        super(new MigLayout("ins 0, gap 0"));
        this.node = node;

        setBorder(new LineBorder(Color.LIGHT_GRAY, BORDER_THICKNESS));
        setToolTipText(buildToolTipText());
        setMinimumSize(MINIMUM_SIZE);
    }

    @Override
    public void paint(Graphics g) {
        super.paint(g);

        Graphics2D g2D = (Graphics2D) g.create();
        g2D.setColor(node.getColor());
        g2D.fillRect(BORDER_THICKNESS, BORDER_THICKNESS,
                getWidth() - 2 * BORDER_THICKNESS,
                getHeight() - 2 * BORDER_THICKNESS);

        if (node.isLabeled()) {
            g2D.setColor(Color.WHITE);
            g2D.fillRect(getWidth() / 4, getHeight() / 4, getWidth() / 4, getHeight() / 4);
        }
        g2D.dispose();
    }

    private String buildToolTipText() {
        List<Instrument> instruments = node.getInstruments();
        StringBuilder sb = new StringBuilder("<html>");

        sb.append("<b>Sector</b> = ").append(node.getValue());
        sb.append("<br>").append("<b>Instruments</b>:").append("</br>");
        for (Instrument instrument : instruments) {
            sb.append("<br>").append(" - ").append(instrument.getSymbol()).append("</br>");
        }

        return sb.append("</html>").toString();
    }

    public static void main(String[] args) {
        testMapNodePanel();
    }

    private static void testMapNodePanel() {
        final MapNode testNode = new MapNode(new SomNode(), new String[] {"INDEX"}, 0, 0);
        testNode.setColor(Color.GREEN);

        SwingUtilities.invokeLater(new Runnable() {

            public void run() {
                MapNodePanel mapNodePanel = new MapNodePanel(testNode);

                JPanel contentPane = new JPanel(new MigLayout("fill, ins 0"));
                contentPane.add(mapNodePanel, "center, h 20, w 20");

                JFrame mainFrame = new JFrame();
                mainFrame.setContentPane(contentPane);
                mainFrame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
                mainFrame.setSize(new Dimension(100, 100));
                mainFrame.setVisible(true);
            }
        });
    }
}
